<template>
  <div style="background-color: #fff;padding:10px 0px">
    <div v-if="detailsArr.length>0">
      <div v-for="(item,index) in detailsArr" :key="index">
        <div class="L-detail-title-row" @click="item.expand = !item.expand">
          <span class="L-text L-primary-text-color">
            <i class="iconfont icon-yuanzhu" style="color:#1683f7"></i>
            {{item.groupStitle}}
          </span>
          <i class="iconfont" :class="!item.expand ? 'icon-zhankai1' :'icon-xiayibu2'"></i>
        </div>
        <van-cell-group v-show="!item.expand">
          <template v-for="(fitem,findex) in item.groupvalue" :key="findex">
            <DetailItem :detailItem="fitem"></DetailItem>
          </template>
        </van-cell-group>
      </div>
    </div>
  </div>

  <van-cell-group class="L-margin-top-20" style="padding: 10px">

    <div class="L-form-title-row" style="width:100%">
      <div>
        <i class="iconfont icon-yuanzhu" style="color:#1683f7"></i>
        <span class="L-text L-primary-text-color">客户列表</span>
      </div>
    </div>

    <div v-for="(item,index) in customerArr" :key="index">
      <van-row>
        <van-col :span="4" style="text-align: center;">
          <img src="@/assets/images/default_company.png" style="width: 40px;">
        </van-col>
        <van-col :span="16">
          <div class="L-text">{{item.sname}}</div>
          <div class="L-mini-text L-secondary-text-color">{{item.saddress}}</div>
        </van-col>
        <van-col :span="4" style="text-align: center;">
          <span style="color:#1c71fb;font-size:14px" @click="handleNavigation(item)">
            导航
            <!-- <i class="iconfont icon-daohang"></i> -->
          </span>
        </van-col>
      </van-row>
      <van-divider />
    </div>
  </van-cell-group>

  <div class="L-bottom-space"></div>

  <div class="L-bottom-row" v-if="operation.length>0" :style="{justifyContent:operation.length==1 ? 'center' : 'space-evenly'}">
    <template v-for="(item,index) in operation" :key="index">
      <div class="L-operate-btn" @click="handleClickOperation(item)" v-if="index<2">{{item.title}}</div>
    </template>

    <van-popover v-model:show="showPopover" placement="top-end" :actions="operationMoreActions" @select="handleClickOperation">
      <template #reference>
        <div v-if="operation.length>2" class="L-operate-more-btn">
          <i class="iconfont icon-icon_more L-title"></i>
        </div>
      </template>
    </van-popover>
  </div>

  <!-- 编辑弹窗 -->
  <!-- <van-popup v-model:show="showEditPopup" position="bottom" style="width: 100%;height:100%">
    <Form v-if="showEditPopup" :loadapi="editApi" :loadParams="editParams" :submitapi="editSubmitapi" :callBack="handleEditSubmit" mode="pop" :idobject="idobject"></Form>
  </van-popup> -->

  <!-- 地图弹窗 -->
  <van-popup round v-model:show="showeMapPopup" position="bottom" style="width: 100%;height:90%">
    <Map v-if="showeMapPopup" :map-data="currentMapInfo"></Map>
  </van-popup>
  <!-- 场景弹窗 -->
  <van-action-sheet cancel-text="取消" v-model:show="showScenarioPopover" :actions="scenarioArr" @select="handleClickAdd" />

</template>

<script setup lang="ts">
import DetailItem from "@/components/base/Detail/DetailItem.vue";
import { useRouterStore } from "@/stores/router";
const routerStore = useRouterStore();
import Map from "@/components/base/Map/Map.vue";
import { apiConfigurable } from "@/request/api/api";
import { ref, reactive, onMounted } from "vue";
import {
  closeToast,
  showLoadingToast,
  showConfirmDialog,
  showToast,
} from "vant";
import { useRoute, useRouter } from "vue-router";
const router = useRouter();
const route = useRoute();

const idobject = ref("");
const itemid = ref("");
const idtemplate = ref("");

idobject.value = route.query.idobject as string;
itemid.value = route.query.itemid as string;
idtemplate.value = route.query.idtemplate as string;
// const item = JSON.parse(route.query.item);

import type { planItemVO } from "@/interface/interface"
const planItem = ref<planItemVO>({});
// planItem.value = JSON.parse(route.query.item);

const operation = ref([]);
const operationMoreActions = ref([]);
const showPopover = ref(false);
const customerArr = ref([]);
const detailsArr = ref([]);

const loading = ref(false);

interface params {
  [idx: string]: any;
}

onMounted(() => {
  getData();
  getScenario();
});

function getData() {
  const { idobject, itemid, idtemplate } = route.query;
  const params: params = {};
  params[`${idobject}_id`] = itemid;
  params[`${idobject}_idtemplate`] = idtemplate;

  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });
  loading.value = true;
  const url = `${idobject}.check.do`;

  apiConfigurable(url, params).then(async (res) => {
    const jsondata = res.data.jsondata;
    const mxList = res.data.mxList;
    detailsArr.value = res.data.jsondata.Details;

    if (jsondata.operation) {
      operation.value = jsondata.operation || [];
      if (operation.value.length > 2) {
        operationMoreActions.value = operation.value
          .filter((item, index) => index > 1)
          .map((item) => {
            return { text: item.title, ...item };
          });
      }
    }

    if (mxList) {
      customerArr.value = res.data.mxList;
    }

    loading.value = false;
    closeToast();
  });
}

// 地图=============================
interface mapInfo {
  name: string;
  address: string;
  lat: string | number;
  lng: string | number;
}

const showeMapPopup = ref(false);
const currentMapInfo = reactive<mapInfo>({
  name: "",
  address: "",
  lat: "",
  lng: "",
});

function handleNavigation(item) {
  currentMapInfo.name = item.sname;
  currentMapInfo.address = item.saddress;
  // currentMapInfo.lat = item.lonlat.split(",")[1];
  // currentMapInfo.lng = item.lonlat.split(",")[0];
  showeMapPopup.value = true;
}

function handleClickOperation(action) {
  console.log("action", action);
  const { mobileFunc } = action;
  switch (mobileFunc) {
    case "edit":
      toEdit();
      break;
    case "del":
      handleDel();
      break;
    case "audit":
      handleAudit();
      break;

    case "unaudit":
      handleUnaudit();
      break;

    case "start":
      handleStart();
      break;
    case "stop":
      handleStop();
      break;

    case "finish":
      handleFinish();
      break;
    case "addplan":
      handleAddPlan();
      break;
  }
}

//编辑
const showEditPopup = ref(false);
const editApi = ref("");
const editSubmitapi = ref("");
const editParams = reactive<params>({});

function toEdit() {
  const { idobject, idtemplate, stitle, itemid } = route.query;

  const path = `/jhglForm`;
  const { jhgl_jhcj_ref, jhgl_jhcj } = planItem.value;

  const query = {
    itemid,
    idobject,
    idtemplate,
    scenarioId: jhgl_jhcj,
    scenarioTitle: jhgl_jhcj_ref,
  };

  router.replace({
    path,
    query,
  });
  // showEditPopup.value = true;
  // const { idobject, itemid } = route.query;
  // editApi.value = `${idobject}.edit.do`;
  // editSubmitapi.value = `${idobject}.editsave.do`;
  // editParams[`${idobject}_id`] = itemid;
}

interface scenarioItemType {
  name: string;
  id: number;
  selectobj: string;
  accountobj: string;
}

function handleClickAdd(scenarioItem: scenarioItemType) {
  const { idobject, idtemplate, stitle } = route.query;
  const path = `/jhglForm`;

  const { name, id, selectobj, accountobj } = scenarioItem;



  const query = {
    idobject:'jhgl',
    idtemplate,
    stitle,
    scenarioId: id,
    scenarioTitle: name,
    scenarioSelectobj: selectobj,
    scenarioAccountobj: accountobj,
    customerArr:JSON.stringify(customerArr.value)
  };
  showScenarioPopover.value = false;

  router.replace({
    path,
    query,
  });
}

const scenarioArr = ref<scenarioItemType[]>([]);
const showScenarioPopover = ref(false);
function getScenario() {
  apiConfigurable("scenario.getlist.do").then((res) => {
    if (res.code === 0) {
      const scenarios = Object.entries(res.data.scenarios) as [];
      const scenarioInfos = res.data.scenarioInfos;

      scenarioArr.value = scenarios.map((item, index) => {
        return {
          name: item[1],
          id: item[0],
          selectobj: scenarioInfos[item[0]].selectobj,
          accountobj: scenarioInfos[item[0]].accountobj,
        };
      });
    }
  });
}

// 生成计划
function handleAddPlan() {
  showScenarioPopover.value = true
}

//开始
function handleStart() {
  // console.log("^^^^",planItem.value)
  // return
  const { itemid, idobject } = route.query;
  const realObj = idobject;
  const realId = itemid;
  const data = {
    [realObj + "_status"]: planItem.value[`${realObj}_status`],
    [realObj + "_status_enum"]: planItem.value[`${realObj}_status_enum`],
    [realObj + "_id"]: realId,
  };
  const url = realObj + ".start.do";

  operateApi(url, data);
}

//停止
function handleStop() {
  const { itemid, idobject } = route.query;
  const realObj = idobject;
  const realId = itemid;
  const data = {
    [realObj + "_status"]: planItem.value[`${realObj}_status`],
    [realObj + "_status_enum"]: planItem.value[`${realObj}_status_enum`],
    [realObj + "_id"]: realId,
  };
  const url = realObj + ".stop.do";

  operateApi(url, data);
}

//结束
function handleFinish() {
  const { itemid, idobject } = route.query;
  const realObj = idobject;
  const realId = itemid;
  const data = {
    [realObj + "_status"]: planItem.value[`${realObj}_status`],
    [realObj + "_status_enum"]: planItem.value[`${realObj}_status_enum`],
    [realObj + "_id"]: realId,
  };
  const url = realObj + ".finish.do";

  operateApi(url, data);
}
//删除
function handleDel() {
  const { itemid, idobject } = route.query;
  showConfirmDialog({
    title: "标题",
    message: "确认要删除当前数据吗?",
  }).then(() => {
    const realObj = idobject;
    const realId = itemid;
    const data = { [realObj + "_id"]: realId };
    const url = realObj + ".del.do";

    operateApi(url, data);
  });
}
//审核
function handleAudit() {
  const { itemid, idobject } = route.query;
  const realObj = idobject;
  const realId = itemid;
  const data = { [realObj + "_id"]: realId };
  const url = realObj + ".audit.do";

  operateApi(url, data);
}
//弃审
function handleUnaudit() {
  const { itemid, idobject } = route.query;
  const realObj = idobject;
  const realId = itemid;
  const data = { [realObj + "_id"]: realId };
  const url = realObj + ".unaudit.do";
  operateApi(url, data);
}

//执行操作接口
function operateApi(url, data) {
  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });

  apiConfigurable(url, data).then((res) => {
    showToast("操作成功");
    setTimeout(() => {
      routerStore.mode = "reload";
      router.go(-1);
    }, 1000);
  });
}
</script>

<style scoped>
.L-jhgl-box {
  padding: 15px;
}
</style>